﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Collections;
using PJ.Data.WCF;
using PJ.Framework;

namespace PJ.Data
{
    public abstract class ObjectWCFProxyProvider<C, S, D, I> : IDisposable, IObjectProvider<I>
        where I : class, IObjectData
        where D : BaseObjectData, I, new()
        where S : class, IObjectWCFProvider<D>
        where C : ObjectProviderClient<S, D>, new()
    {

        #region Constructor

        protected ObjectWCFProxyProvider(IObjectDataCache<I> cache)
        {
            if (cache == null)
                throw new ArgumentNullException("cache");
            _Cache = cache;
        }

        #endregion



        #region Interface implementation

        public void Dispose()
        {
            if (m_ClientBase != null)
            {
                ClientBase = null;
            }
        }

        public I GetData(string globalId, GetDataMode mode)
        {
            try
            {
                I data = null;
                if ((mode & GetDataMode.UseCache) == GetDataMode.UseCache && Cache != null)
                    data = Cache.Find(globalId);
                if (data == null)
                    data = ClientBase.GetData("", globalId, (int)mode) as I;
                if (data == null)
                    if ((mode & GetDataMode.Find) == GetDataMode.Find)
                        return null;
                    else
                        throw new DataNotFoundException("globalId", globalId);
                if (Cache != null)
                    return Cache.Add(data);
                else
                    return data;
            }
            catch (Exception ex)
            {
                ClientBase = null;
                ExceptionManager.Handle(ex);
                throw ex;
            }
        }

        public List<I> GetList(string[] globalIds, GetDataMode mode)
        {
            Dictionary<string, I> inStorage = null;
            Dictionary<string, I> inCache = null;    // List of objects found in cache
            string[] toGetIds;                       // List of ids to fetch from storage

            if ((mode & GetDataMode.UseCache) == GetDataMode.UseCache && Cache != null) // Use cache if UseCache mode and cache exists
                inCache = Cache.Find(globalIds, out toGetIds);
            else
                toGetIds = globalIds;
            if (toGetIds != null && toGetIds.Count() != 0) // Some ids are not found in cache, get them from storage
            {
                try
                {
                    List<D> listData = ClientBase.GetList("", toGetIds, (int)mode);
                    if (listData != null)
                    {
                        inStorage = new Dictionary<string, I>();
                        foreach (I data in listData)
                        {
                            if (Cache != null)
                                Cache.Add(data);
                            inStorage.Add(data.GlobalId, data);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ClientBase = null;
                    ExceptionManager.Handle(ex);
                    throw ex;
                }
            }
            List<I> list = ListUtil.Fusion<I>(globalIds, inCache, inStorage); // Create the object list on the same order as the GlobalId list
            if ((mode & GetDataMode.Find) != GetDataMode.Find && list.Count != globalIds.Count())
                throw new DataNotFoundException("GlobalIds", globalIds.ToString());
            return list;
        }


        public bool Exist(string globalId)
        {
            try
            {
                return ClientBase.Exist("", globalId);
            }
            catch (Exception ex)
            {
                ClientBase = null;
                ExceptionManager.Handle(ex);
                throw ex;
            }
        }

        public void Delete(string globalId)
        {
            if (globalId == null || globalId == "")
                throw new ArgumentNullException("globalId");
            try
            {
                ClientBase.Delete("", globalId);
            }
            catch (Exception ex)
            {
                ClientBase = null;
                ExceptionManager.Handle(ex);
                throw ex;
            }
        }

        public I PersistAndGet(I data)
        {
            if (data == null)
                throw new ArgumentNullException("data");
            if (data.GlobalId == null || data.GlobalId == "")
                throw new ArgumentNullException("GlobalId is null or empty", "data");
            try
            {
                I retData = ClientBase.PersistAndGet("", ToContract(data)) as I;
                if (Cache != null)
                    return Cache.Add(retData);
                else
                    return retData;
            }
            catch (Exception ex)
            {
                ClientBase = null;
                ExceptionManager.Handle(ex);
                throw ex;
            }
        }

        public void Persist(I data)
        {
            if (data == null)
                throw new ArgumentNullException("data");
            if (data.GlobalId == null || data.GlobalId == "")
                throw new ArgumentNullException("GlobalId is null or empty", "data");
            try
            {
                ClientBase.Persist("", ToContract(data));
            }
            catch (Exception ex)
            {
                ClientBase = null;
                ExceptionManager.Handle(ex);
                throw ex;
            }
        }

        public virtual I CreateNewItem()
        {
            return new D();
        }



        #endregion

        #region Interface override

        IObjectData IObjectProvider.GetData(string globalId, GetDataMode mode)
        {
            return GetData(globalId, mode);
        }

        IEnumerable IObjectProvider.GetList(string[] globalIds, GetDataMode mode)
        {
            return GetList(globalIds, mode);
        }


        IObjectData IObjectProvider.PersistAndGet(IObjectData data)
        {
            return PersistAndGet((I)data);
        }

        void IObjectProvider.Persist(IObjectData data)
        {
            Persist((I)data);
        }

        IObjectData IObjectProvider.CreateNewItem()
        {
            return CreateNewItem();
        }

        #endregion


        #region Protected

        protected D CreateNewItem(IObjectData data)
        {
            return (D)CreateNewItem().Init(data);
        }

        protected D ToContract(IObjectData data)
        {
            if (data == null)
                return null;
            D temp = data as D;
            if (temp == null)
                return CreateNewItem(data);
            else
                return temp;
        }

        protected IObjectDataCache<I> Cache
        {
            get { return _Cache; }
        }

        protected C ClientBase
        {
            get
            {
                if (m_ClientBase != null)
                    if (m_ClientBase.State == CommunicationState.Faulted)
                    {
                        m_ClientBase.Abort();
                        ClientBase = null;
                    }
                if (m_ClientBase == null)
                {
                    m_ClientBase = new C();
                }
                return m_ClientBase;
            }
            set
            {
                if (m_ClientBase != null)
                    m_ClientBase.Dispose();
                m_ClientBase = value;
            }
        }

        #endregion

        #region Field

        private readonly IObjectDataCache<I> _Cache;
        private C m_ClientBase;


        #endregion

    }
}
